<template>
  <div class="realtime-text-component" :style="getComponentStyle()">
    <div class="data-display">
      <span class="label" v-if="props.showLabel">{{ props.label || props.dataPointId }}:</span>
      <span class="value" :class="getValueClass()">
        {{ formattedValue }}
      </span>
      <span class="unit" v-if="props.showUnit && unit">{{ unit }}</span>
    </div>
    <div class="status-indicator" v-if="props.showStatus">
      <span class="status-dot" :class="statusClass"></span>
      <span class="status-text">{{ statusText }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { useRealtimeDataStore } from '@/stores/realtime-data';

const props = defineProps({
  dataPointId: {
    type: String,
    default: 'demo_point_1',
    required: true
  },
  label: {
    type: String,
    default: ''
  },
  showLabel: {
    type: Boolean,
    default: true
  },
  showUnit: {
    type: Boolean,
    default: true
  },
  showStatus: {
    type: Boolean,
    default: true
  },
  precision: {
    type: Number,
    default: 2
  },
  fontSize: {
    type: String,
    default: '16px'
  },
  color: {
    type: String,
    default: '#333333'
  },
  backgroundColor: {
    type: String,
    default: 'transparent'
  },
  borderRadius: {
    type: String,
    default: '4px'
  },
  padding: {
    type: String,
    default: '8px'
  },
  // 数值范围告警配置
  warningMin: {
    type: Number,
    default: undefined
  },
  warningMax: {
    type: Number,
    default: undefined
  },
  errorMin: {
    type: Number,
    default: undefined
  },
  errorMax: {
    type: Number,
    default: undefined
  }
});

// 获取实时数据Store
const realtimeStore = useRealtimeDataStore();
const componentId = `realtime-text-${Math.random().toString(36).substr(2, 9)}`;

// 响应式数据
const currentValue = ref<any>(null);
const dataPoint = ref<any>(null);
const isConnected = ref(false);

// 订阅数据点
const subscribeToData = () => {
  if (props.dataPointId) {
    realtimeStore.subscribe(props.dataPointId, componentId);
    console.log(`Subscribed to data point: ${props.dataPointId}`);
  }
};

// 取消订阅
const unsubscribeFromData = () => {
  if (props.dataPointId) {
    realtimeStore.unsubscribe(props.dataPointId, componentId);
    console.log(`Unsubscribed from data point: ${props.dataPointId}`);
  }
};

// 更新数据
const updateData = () => {
  if (props.dataPointId) {
    const point = realtimeStore.getDataPoint(props.dataPointId);
    if (point) {
      dataPoint.value = point;
      currentValue.value = point.value;
      isConnected.value = true;
    } else {
      // 如果没有找到数据点，尝试使用全局方法（兼容旧版本）
      if (typeof (window as any).$getRealtimeData === 'function') {
        const value = (window as any).$getRealtimeData(props.dataPointId);
        if (value !== undefined) {
          currentValue.value = value;
          isConnected.value = true;
        }
      }
    }
  }
};

// 监听数据变化
watch(
  () => realtimeStore.dataPoints,
  () => {
    updateData();
  },
  { deep: true }
);

// 监听数据点ID变化
watch(
  () => props.dataPointId,
  (newId, oldId) => {
    if (oldId) {
      unsubscribeFromData();
    }
    if (newId) {
      subscribeToData();
      updateData();
    }
  }
);

// 格式化显示值
const formattedValue = computed(() => {
  if (currentValue.value === null || currentValue.value === undefined) {
    return '--';
  }

  if (typeof currentValue.value === 'number') {
    return currentValue.value.toFixed(props.precision);
  }

  return String(currentValue.value);
});

// 获取单位
const unit = computed(() => {
  return dataPoint.value?.unit || '';
});

// 获取数值状态类
const getValueClass = () => {
  if (typeof currentValue.value !== 'number') {
    return '';
  }

  const value = currentValue.value;

  // 错误范围检查
  if (props.errorMin !== undefined && value < props.errorMin) return 'error';
  if (props.errorMax !== undefined && value > props.errorMax) return 'error';

  // 警告范围检查
  if (props.warningMin !== undefined && value < props.warningMin) return 'warning';
  if (props.warningMax !== undefined && value > props.warningMax) return 'warning';

  return 'normal';
};

// 状态指示器
const statusClass = computed(() => {
  if (!isConnected.value) return 'disconnected';
  if (dataPoint.value?.quality === 'bad') return 'error';
  if (dataPoint.value?.quality === 'uncertain') return 'warning';
  return 'connected';
});

const statusText = computed(() => {
  if (!isConnected.value) return '未连接';
  if (dataPoint.value?.quality === 'bad') return '数据异常';
  if (dataPoint.value?.quality === 'uncertain') return '数据不确定';
  return '正常';
});

// 组件样式
const getComponentStyle = () => {
  return {
    fontSize: props.fontSize,
    color: props.color,
    backgroundColor: props.backgroundColor,
    borderRadius: props.borderRadius,
    padding: props.padding,
    display: 'inline-flex',
    alignItems: 'center',
    gap: '8px',
    border: '1px solid #e0e0e0',
    minWidth: '120px'
  };
};

// 生命周期
onMounted(() => {
  subscribeToData();
  updateData();

  // 定期更新数据（作为备用机制）
  const interval = setInterval(updateData, 1000);

  onUnmounted(() => {
    clearInterval(interval);
    unsubscribeFromData();
  });
});

onUnmounted(() => {
  unsubscribeFromData();
});
</script>

<style scoped>
.realtime-text-component {
  font-family: 'Arial', sans-serif;
  user-select: none;
}

.data-display {
  display: flex;
  align-items: center;
  gap: 4px;
}

.label {
  font-weight: 500;
}

.value {
  font-weight: bold;
  min-width: 60px;
  text-align: right;
}

.value.normal {
  color: #52c41a;
}

.value.warning {
  color: #faad14;
}

.value.error {
  color: #ff4d4f;
}

.unit {
  font-size: 0.9em;
  color: #666;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.status-dot.connected {
  background-color: #52c41a;
}

.status-dot.warning {
  background-color: #faad14;
}

.status-dot.error {
  background-color: #ff4d4f;
}

.status-dot.disconnected {
  background-color: #d9d9d9;
}

.status-text {
  color: #666;
}
</style>
